﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Marmat.Forms;
using Marmat.Foundation;

namespace Marmat.Template.WinForm
{
    public partial class DataDictionaryForm : Marmat.Forms.Form, Marmat.Foundation.IDataDictionaryManagerForm
    {
        public DataDictionaryForm()
        {
            InitializeComponent();
            manager = Marmat.FrameWork.SystemCommand.GetService<Marmat.Foundation.IDataDictionaryManager>();
            dataDictionary = Marmat.FrameWork.SystemCommand.GetService<Marmat.Foundation.IDataDictionary>();
        }

        Marmat.Foundation.IDataDictionaryManager manager;
        Marmat.Foundation.IDataDictionary dataDictionary;
        Marmat.Foundation.IDataDictionaryCategory selection;
        /// <summary>
        /// 存储角色设置按钮区域的图标。
        /// </summary>
        Dictionary<IDataDictionaryCategory, Rectangle> settingRectangleCollection = new Dictionary<IDataDictionaryCategory, Rectangle>();

        void Marmat.Foundation.IDataDictionaryManagerForm.Show()
        {
            this.ShowDialog();
        }

        void LoadData()
        {
            this.treeView1.Nodes.Clear();
            var categoryCollection = this.manager.GetCategoryCollection();
            buildTreeNode(this.treeView1.Nodes, categoryCollection.Where(x => string.IsNullOrEmpty(x.Parent)).OrderBy(x => x.Index));
            this.treeView1.Invalidate();
            void buildTreeNode(Marmat.Forms.Skin.TreeNodeCollection nodes, IEnumerable<IDataDictionaryCategory> categories)
            {
                foreach (var category in categories)
                {
                    var node = new Forms.Skin.TreeNode();
                    node.Name = category.Key;
                    node.Text = category.Name;
                    node.Tag = category;
                    nodes.Add(node);
                    buildTreeNode(node.Nodes, categoryCollection.Where(x => x.Parent == category.Key).OrderBy(x => x.Index));
                }
            }
        }

        private void DataDictionaryForm_Load(object sender, EventArgs e)
        {
            this.LoadData();
        }

        private void treeView1_MeasureNode(object sender, Forms.Skin.MeasureTreeNodeEventArgs e)
        {
            e.Size = new Size(this.treeView1.Width, e.Size.Height);
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            settingRectangleCollection.Clear();
            base.OnPaint(e);
        }

        private void treeView1_DrawNode(object sender, Marmat.Forms.Skin.DrawTreeNodeEventArgs e)
        {
            Color backColor = Color.Transparent;
            if (e.Node == this.treeView1.SelectedNode)
                backColor = Color.FromArgb(179, 224, 255);
            else if (e.Node == this.treeView1.MouseMoveNode)
                backColor = Color.FromArgb(226, 240, 255);
            using SolidBrush brush = new SolidBrush(backColor);
            e.Graphics.FillRectangle(brush, e.Bounds);
            int left = e.Node.Level * this.treeView1.Indent + 12;

            Image img;
            if (e.Node.Nodes.Count > 0)
            {
                if (e.Node.IsExpanded)
                    img = Marmat.Template.WinForm.Properties.Resources.expand_icon;
                else
                    img = Marmat.Template.WinForm.Properties.Resources.collapse_icon;
                e.Graphics.DrawImage(img, new Rectangle(left, e.Bounds.Top + (e.Bounds.Height - img.Height) / 2, img.Width, img.Height), new Rectangle(0, 0, img.Width, img.Height), GraphicsUnit.Pixel);
            }
            left += 30;
            Rectangle bounds = new Rectangle(left, e.Bounds.Y, this.treeView1.ClientSize.Width - left, e.Bounds.Height);
            TextRenderer.DrawText(e.Graphics, e.Node.Text, this.treeView1.Font, bounds, Color.Black, Color.Transparent, TextFormatFlags.Left | TextFormatFlags.VerticalCenter);

            if (this.treeView1.SelectedNode == e.Node)
            {
                img = Properties.Resources.setting_icon;
                bounds = new Rectangle(bounds.Right - img.Width - 6, bounds.Top + (bounds.Height - img.Height) / 2, img.Width, img.Height);
                this.settingRectangleCollection[e.Node.Tag as IDataDictionaryCategory] = bounds;
                e.Graphics.DrawImage(img, bounds);
            }
        }

        private void treeView1_NodeMouseClick(object sender, Forms.Skin.TreeNodeMouseClickEventArgs e)
        {
            var settingNode = settingRectangleCollection.FirstOrDefault(x => x.Value.Contains(e.Location)).Key;
            if (settingNode is not null)
            {
                this.contextMenuStrip1.Tag = e.Node;
                this.contextMenuStrip1.Show(this.treeView1, e.Location);
                return;
            }

            if (e.Node.Nodes.Count > 0)
            {
                if (e.Node.IsExpanded)
                    e.Node.Collapse();
                else
                    e.Node.Expand();
            }
        }

        private void treeView1_AfterSelect(object sender, Forms.Skin.TreeViewEventArgs e)
        {
            if (e.Node.Tag is Marmat.Foundation.IDataDictionaryCategory category && !category.IsGroup)
            {
                var collection = this.dataDictionary.GetDataDictionary(category.Key).OrderBy(x => x.Index);
                this.gridControl1.DataSource = collection.ToList();
                this.selection = category;
                this.gridControl1.ShowAddNew = true;
                this.gridControl1.OpenDeleteColumn((args) =>
                {
                    if (args.Row is IDataDictionaryItem item)
                    {
                        if (Marmat.Forms.MessageBox.Show("确定要删除此条记录吗？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                        {
                            this.manager.DeleteDictionaryItem(new string[] { item.Id });
                            args.GridControl.DeleteRow(args.RowHandle);
                            args.GridControl.RefreshDataSource();
                        }
                    }
                });
            }
            else
            {
                this.gridControl1.DataSource = null;
                this.selection = null;
                this.gridControl1.ShowAddNew = false;
                this.gridControl1.CloseDeleteColumn();
            }
        }

        /// <summary>
        /// 创建分组
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void skinButton1_Click(object sender, EventArgs e)
        {
            CreateDataDictionaryForm frm = new CreateDataDictionaryForm();
            frm.textBox1.ReadOnly = BooleanEnum.True;
            if (frm.ShowDialog() == DialogResult.OK)
            {
                string parent = string.Empty;
                string name = frm.textBox2.Value;
                if (frm.comboBox1.Value is IDataDictionaryCategory category)
                    parent = category.Name;
                this.manager.CreateCategory(parent, name);
            }

            //string name = "";
            //if (InputValue.Show(ref name, "创建分组", "请输入分组的名称："))
            //{
            //    var category = this.manager.CreateCategory(string.Empty, name);
            //    Marmat.Forms.Skin.TreeNodeCollection collection = this.treeView1.Nodes;
            //    var node = collection.Add(category.Key, category.Name);
            //    node.Tag = category;

            //    if (node.Parent is not null)
            //        node.Parent.Expand();
            //    this.treeView1.SelectedNode = node;
            //}
        }

        /// <summary>
        /// 创建字典
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void skinButton2_Click(object sender, EventArgs e)
        {
            CreateDataDictionaryForm frm = new CreateDataDictionaryForm();
            if (this.selection is not null && !this.selection.IsGroup)
                frm.comboBox1.Value = this.selection.Key;
            if (frm.ShowDialog() == DialogResult.OK)
            {
                if (frm.comboBox1.Value is IDataDictionaryCategory category)
                    this.manager.CreateDictionary(category.Key, frm.textBox1.Value, frm.textBox2.Value);
                this.LoadData();
            }
        }

        private void gridControl1_CellNewRowLink(object sender, EventArgs e)
        {
            if (this.selection is not null)
            {
                CreateDataDictionaryItemForm frm = new CreateDataDictionaryItemForm();
                frm.Text = $"创建字典 - {this.selection.Name}";
                if (frm.ShowDialog() == DialogResult.OK)
                {
                    DataDictionaryItem item = new DataDictionaryItem();
                    item.Value = frm.textBox1.Value;
                    item.Text = frm.textBox2.Value;
                    item.Description = frm.memoBox1.Value;
                    this.manager.AddDictionaryItem(this.selection.Key, item);
                    var collection = this.dataDictionary.GetDataDictionary(this.selection.Key);
                    this.gridControl1.DataSource = collection.ToList();
                }
            }
        }

        private void gridControl1_RowCellDoubleClick(object sender, Forms.Views.Grid.RowColEventArgs e)
        {
            if (e.Row is DataDictionaryItem item)
            {
                CreateDataDictionaryItemForm frm = new CreateDataDictionaryItemForm();
                frm.Text = $"修改字典 - {this.selection.Name}";
                frm.textBox1.Value = item.Value;
                frm.textBox2.Value = item.Text;
                frm.memoBox1.Value = item.Description;
                frm.button3.Visible = true;
                DialogResult dialog = frm.ShowDialog();
                if (dialog == DialogResult.OK)
                {
                    item.Value = frm.textBox1.Value;
                    item.Text = frm.textBox2.Value;
                    item.Description = frm.memoBox1.Value;
                    this.manager.RenameDictionaryItem(item.Id, item.Value, item.Text, item.Description);
                }
                else if (dialog == DialogResult.Retry)
                {
                    this.manager.DeleteDictionaryItem(new string[] { item.Id });
                    var collection = this.dataDictionary.GetDataDictionary(this.selection.Key);
                    this.gridControl1.DataSource = collection.ToList();
                }
            }
        }

        private void contextMenuStrip1_ItemClicked(object sender, System.Windows.Forms.ToolStripItemClickedEventArgs e)
        {
            switch (e.ClickedItem.Name)
            {
                case nameof(重命名ToolStripMenuItem):
                    {
                        if (this.contextMenuStrip1.Tag is Marmat.Forms.Skin.TreeNode node && node.Tag is IDataDictionaryCategory category)
                        {
                            CreateDataDictionaryForm frm = new CreateDataDictionaryForm();
                            frm.textBox1.Value = category.Key;
                            frm.textBox1.ReadOnly = BooleanEnum.True;
                            frm.textBox2.Value = category.Name;
                            frm.comboBox1.Value = category.Parent;
                            frm.Text = "修改字典";
                            if (frm.ShowDialog() == DialogResult.OK)
                            {
                                string parent = string.Empty;
                                string name = frm.textBox2.Value;
                                if (frm.comboBox1.Value is IDataDictionaryCategory dictionaryCategory)
                                    parent = dictionaryCategory.Name;
                                this.manager.UpdateCategory(category.Key, name, parent);
                                LoadData();
                            }
                        }
                    }
                    break;
                case nameof(删除ToolStripMenuItem):
                    {
                        if (this.contextMenuStrip1.Tag is Marmat.Forms.Skin.TreeNode node && node.Tag is IDataDictionaryCategory category)
                        {
                            if (Marmat.Forms.MessageBox.Show($"删除“{category.Name}”，组内的字典信息都将清空。是否继续删除？", $"确认要删除“{category.Name}”吗？", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                            {
                                List<string> userCollection = new List<string>();
                                userCollection.Add(category.Key);
                                if (node.Nodes.Count > 0)
                                    this.GetAllNodeCollection(node.Nodes).Select(x => (x.Tag as IDataDictionaryCategory).Key).ToList().ForEach(x => userCollection.Add(x));
                                this.manager.DeleteCategory(userCollection.ToArray());
                                this.treeView1.SelectedNode = node.PrevNode;
                                node.Remove();
                            }
                        }
                    }
                    break;
            }
        }

        private List<Marmat.Forms.Skin.TreeNode> GetAllNodeCollection(Marmat.Forms.Skin.TreeNodeCollection nodes)
        {
            List<Marmat.Forms.Skin.TreeNode> items = new List<Forms.Skin.TreeNode>();
            foreach (Marmat.Forms.Skin.TreeNode node in nodes)
            {
                items.Add(node);
                if (node.Nodes.Count > 0)
                    items.AddRange(GetAllNodeCollection(node.Nodes));
            }
            return items;
        }

        private void gridControl1_CustomDrawCell(object sender, Forms.Views.GridControl.RowCellCustomDrawEventArgs e)
        {
            if (e.Column.Name == "Text" && (e.CellValue is null || string.IsNullOrEmpty(e.CellValue.ToString())))
            {
                if (e.Row is DataDictionaryItem item)
                {
                    e.DisplayText = item.Value;
                    e.Appearance.ForeColor = Color.Gray;
                }
            }
        }
    }
}
